AddEvent(window, 'load', HideOnLoad);
AddEvent(window, 'load', BackgroundCheck);

/**
 * Hide elements when loading the page
 */
function HideOnLoad()
{
	midori.get('.hideonload').apply('style.display = "none"');
}

/**
 * Attach function to an event
 * From http://www.quirksmode.org/js/eventSimple.html
 */
function AddEvent(obj, evt, fn)
{
	if (obj.addEventListener)
		obj.addEventListener(evt, fn, false);
	else if (obj.attachEvent)
		obj.attachEvent('on' + evt, function() { fn.call(obj); });
}

/**
 * Remove function from an event
 * From http://www.quirksmode.org/js/eventSimple.html
 */
function RemoveEvent(obj, evt, fn)
{
	if (obj.removeEventListener)
		obj.removeEventListener(evt, fn, false);
	else if (obj.detachEvent)
		obj.detachEvent('on' + evt, fn);
}

/**
 * Show/hide advanced server information on login page
 */
function ShowAdvanced()
{
	if (this.innerHTML.search('Hide') === -1)
	{
		midoriFX.show('advanced');
		this.innerHTML = 'Hide server information';
	}
	else
	{
		midoriFX.hide('advanced');
		this.innerHTML = 'Manually adjust server parameters';
	}
}

/**
 * Try to optimize the column width on the mailbox overview page.
 */
function ColumnWidth()
{
	var listmail = document.getElementById('listmail');

	if (!listmail)
		return;

	// Get usable amount of width
	var totalwidth = listmail.clientWidth - 20;

	// Checkbox, Flags, and Date are fixed: Don't do anything with them
	totalwidth -= midori.get('.checkbox')[1].clientWidth;
	totalwidth -= midori.get('.flags')[1].clientWidth;
	totalwidth -= midori.get('.date')[1].clientWidth;

	// Use 60% of the rest for the subject, and 40% for the address
	var subject = midori.get('.subject');
	var from = midori.get('.from');

	var subjectwidth = (totalwidth * 0.6) + 'px';
	var fromwidth = (totalwidth * 0.4) + 'px';
	for (var i=0; subject.length>i; i+=1)
	{
		subject[i].style.width = subjectwidth;
		from[i].style.width = fromwidth;
	}
}

/**
 * Toggle all checkboxes either all on or all off
 */
function ToggleAllCheckboxes()
{
	var toggleall = document.getElementById('toggleallcheckboxes');

	if (!toggleall.checked)
		midori.get('input[type=checkbox]').apply('checked = false');
	else
		midori.get('input[type=checkbox]').apply('checked = true');
}

/**
 * Don't go to the next form element when pressing the TAB key inside a
 * textarea, insert a TAB instead
 */
function Textarea()
{
	var t = document.getElementsByTagName('textarea');

	for (var i=0; t.length>i; i++)
	{
		// On TAB, actually insert a TAB instead of changing focus
		AddEvent(t[i], 'keydown', function(e)
		{
			if (!e)
				e = window.event;

			if (e && e.keyCode === 9)
				midori.preventDefault(e);
		});
	}
}

/**
 * Show/Hide custom header field on newmail
 */
function ToggleHeaders()
{
	if (this.innerHTML.search('Hide') === -1)
	{
		midoriFX.show('headerswrap');
		this.innerHTML = 'Hide';
	}
	else
	{
		midoriFX.hide('headerswrap');
		this.innerHTML = 'Show';
	}
}

/**
 * Display confirmation dialog on delete if autoexpunge is true
 */
function Delete(e, autoexpunge)
{
	if (!autoexpunge)
		return true;

	var rows = midori.get('.row');
	var msg = '';
	var delcount = 0;
	for (var i=0; rows.length>i; i+=1)
	{
		if (!rows[i].getElementsByTagName('input')[0].checked)
			continue;

		delcount += 1;
		if (delcount > 10)
			continue;

		var v = rows[i].getElementsByTagName('span')[2].getElementsByTagName('a')[0].innerHTML;
		if (v.length > 70)
			v = v.substring(0, 70) + '...';

		msg += '- <tt>' + v + '</tt><br />\n';
	}

	// No messages selected: Do nothing
	if (msg === '')
		return false;

	if (delcount > 10)
		msg += '... ' + (delcount - 10) + ' more...';

	msg = 'Delete the following messages:<br />\n<br />\n'
		+ msg
		+ '<br />\nAre you sure?';

	answer = ConfirmDialog(e,
	{
		'text': msg,
		'id': 'delete',
		'align': 'left',
		'yes': function()
		{
			var b = document.getElementById('deletebutton');
			b.onclick = undefined;
			b.click();
		}
	});

	if (!answer)
		return false;
}

/**
 * Show a simple yes/no confirm dialog as an alternative to confirm()
 *
 * options is a object with the following properties:
 *
 * text: Text/question to show/ask
 * yes:  Callback to execute when the user clicked "Yes"
 * no:   Callback to execute when the user clicked "No"
 * pos:  Dialog position, either pass a object in the form of {x: 0, y: 0} or pass the string
 *       "mouse" or "mouseleft" to place the window right or left of current mouse position
 *       respectively. Default value is "mouse"
 * align: Align the text left, right, or center (default: center)
 * id:   id attribute (default: not set)
 */
function ConfirmDialog(e, options)
{
	// Set defaults
	if (options.no === undefined)
		options.no = function() {};

	if (options.yes === undefined)
		options.yes = function() {};

	if (options.pos === undefined)
		options.pos = 'mouse';

	if (options.align === undefined)
		options.align = 'center';

	// Does this dialog already exists? If so, destroy it.
	if (options.id)
	{
		var o = document.getElementById('confirm_' + options.id);
		if (o)
		{
			o.style.display = 'none';
			o.parentNode.removeChild(o);
		}
	}

	// Make dialog
	var dialog = document.createElement('div');
	dialog.className = 'confirmdialog';
	if (options.id)
		dialog.id = 'confirm_' + options.id;
	dialog.style.display = 'none';

	var dialogtext = document.createElement('p');
	dialogtext.style.textAlign = options.align;
	dialogtext.innerHTML = options.text;
	dialog.appendChild(dialogtext);
	
	// "Destroy" the dialog
	var destroy = function()
	{
		if (dialog && dialog.parentNode)
		{
			dialog.style.display = 'none';
			dialog.parentNode.removeChild(dialog);
		}
	};

	// Add Keybinds: Close on Escape and 'n', submit on 'y'
	var keybind = function(e)
	{
		if (dialog && dialog.parentNode)
		{
			if (e.keyCode === 27 || e.keyCode === 78)
			{
				options.no();
				destroy();
			}
			else if (e.keyCode === 89)
			{
				options.yes();
				destroy();
			}
		}
	};
	RemoveEvent(window, 'keyup', keybind);
	AddEvent(window, 'keyup', keybind);

	// Set position
	if (options.pos === 'mouse')
		options.pos = GetMousePosition(e);
	else if (options.pos === 'mouseleft')
	{
		var mousepos = GetMousePosition(e);
		mousepos.x -= 220;
		options.pos = mousepos;
	}

	dialog.style.left = options.pos.x + 'px';
	dialog.style.top = options.pos.y + 'px';


	// Make Yes/No buttons
	var yes = document.createElement('span');
	yes.className = 'yes';
	yes.innerHTML = '<u>Y</u>es';
	AddEvent(yes, 'click', function() { options.yes(); destroy(); return true; });
	dialog.appendChild(yes);

	var no = document.createElement('span');
	no.className = 'no';
	no.innerHTML = '<u>N</u>o';
	AddEvent(no, 'click', function() { options.no(); destroy(); return false; });
	dialog.appendChild(no);

	document.getElementsByTagName('body')[0].appendChild(dialog);
	dialog.style.display = 'block';
}

/**
 * Based on: http://www.quirksmode.org/js/events_properties.html
 */
function GetMousePosition(e)
{
	var posx = 0;
	var posy = 0;

	if (e.pageX || e.pageY)
	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY)
	{
		posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
	}

	return {'x': posx, 'y': posy };
}

/**
 * Show help for login form
 */
function LoginFormHelp()
{
	var inp = document.getElementsByTagName('input');

	for (var i=0; inp.length>i; i+=1)
	{
		if (!inp[i].title)
			continue;

		var showhelp = function()
		{
			var next = midori.sibling(this, 'next');
			if (!next.className || next.className.search('formhelp') === -1)
			{
				var help = document.createElement('span');
				help.className = 'formhelp';
				help.innerHTML = this.title;

				var pos = midori.getPos(this);

				help.style.left = (parseInt(pos.x, 10) + (this.type === 'checkbox' ? 0 : 25)) + 'px';
				help.style.top = (parseInt(pos.y, 10) - parseInt(this.offsetHeight, 10) + 1) + 'px';
				if (this.type === 'checkbox')
					help.style.top = (parseInt(help.style.top, 10) - 22) + 'px';

				this.parentNode.insertBefore(help, next);

				// Fix for multi-line boxes
				if (help.offsetHeight > 26)
					help.style.top = (parseInt(help.style.top, 10) - parseInt(help.offsetHeight, 10) + 26) + 'px';
			}
		};

		var hidehelp = function()
		{
			if (document.activeElement === this)
				return;

			var next = midori.sibling(this, 'next');
			if (next.className && next.className.search('formhelp') !== -1)
				this.parentNode.removeChild(next);
		};

		AddEvent(inp[i], 'focus', showhelp);
		AddEvent(inp[i], 'mouseover', showhelp);
		AddEvent(inp[i], 'blur', hidehelp);
		AddEvent(inp[i], 'mouseout', hidehelp);
	}
}

/**
 * Periodically check for new email in the background
 */
function BackgroundCheck()
{
	// Not on the login page ...
	if (document.getElementById('login'))
		return;

	// This updates the <title> to include "<num> new emails :: "
	// If num is 0, we remove the "<num> new mails :: " part ...
	var UpdateTitle = function(num)
	{
		var title = document.getElementsByTagName('title')[0];

		// Update existing new mail
		var s = title.innerHTML.match(/^(\d*) new emails? :: /);
		if (num > 0)
		{
			if (s === null)
				title.innerHTML = num + ' new email' + (num > 1 ? 's' : '') + ' :: ' + title.innerHTML
			else
				title.innerHTML = title.innerHTML.replace(/^\d*/, num);
		}
		else
		{
			if (s !== null)
				title.innerHTML = title.innerHTML.replace(/^\d* new email? :: /, '');
		}
	};

	// Update the favicons
	// Note: this doesn't with with IE (Tested up to 9). No way I can fix this.
	var UpdateFavicon = function(num)
	{
		if (num > 0)
			var img = 'newmail';
		else
			var img = 'nomail';

		var icon = document.getElementsByTagName('link');
		for (var i=0; icon.length > i; i+=1)
		{
			if (icon[i].rel === 'icon')
			{
				var link = document.createElement('link');
				link.href = tpldir + '/' + img + '.png';
				link.rel = 'icon';
				icon[i].parentNode.appendChild(link);
				icon[i].parentNode.removeChild(icon[i]);
			}
		}
	};

	// Show a "notify" bar for new email at the bottom
	var Notify = function(data, totalnew)
	{
		var pl = '';
		var html = '';
		var notify;
		var doappend = false;

		// Check if there's already a div
		notify = document.getElementById('notify');

		// No new mail: Hide!
		if (totalnew === 0)
		{
			if (notify)
			{
				midoriFX.hide('notify', function()
				{
					midori.removeNode(notify);
				});
			}

			return;
		}

		if (!notify)
		{
			var notify = document.createElement('div');
			notify.id = 'notify';
			notify.innerHTML = '';
			doappend = true;
		}

		for (var i=0; data.length>i; i+=1)
		{
			pl = data[i].unseen > 1 ? 's' : '';
			html += data[i].unseen
				+ ' new email' + pl
				+ ' in ' + data[i].mbox + '<br />';
		}

		notify.innerHTML = html;

		if (doappend)
		{
			document.body.appendChild(notify);
			document.body.style.marginBottom = '4em';
			midoriFX.show('notify');
		}
	};

	// Actually perform the check
	var check = new midoriAjax(function()
	{
		var newmail = [];
		var totalnew = 0;

		if (check.responseText === 'STOP')
			return false;

		if (JSON.parse)
			var data = JSON.parse(check.responseText);
		else
			var data = eval('(' + check.responseText + ')');

		// Loop over all the mailboxes
		for (var i=0; data.length>i; i+=1)
		{
			if (data[i].unseen > 0)
			{
				newmail.push(data[i]);
				totalnew += data[i].unseen
			}
		}

		// Always update the title & icon, we will change 'em back to normal if
		// there's no new mail
		Notify(newmail, totalnew);
		UpdateTitle(totalnew);
		UpdateFavicon(totalnew);

		setTimeout(BackgroundCheck, 10000);
	});

	check.post('backgroundcheck.php', '');
}

/**
 * Mark email with uid as read.
 */
function MarkAsRead(uid, timeout)
{
	var t = setTimeout(function()
	{
		var mark = new midoriAjax(function()
		{
			// Nothing to do here
		});

		mark.post('markasread.php', 'uid=' + uid);
	}, timeout);

}
